package com.example.client.controller.topic;

import com.example.commonapi.dto.ImgUploadDTO;
import com.example.commonapi.dto.UserAndTopic;
import com.example.commonapi.pojo.Topic;
import com.example.commonapi.pojo.UAT;
import com.example.commonapi.pojo.User;
import com.example.topicservice.service.TopicService;
import com.example.userservice.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class TopicRestController {
    private static final Log logger = LogFactory.getLog(TopicRestController.class);
    private static final String EDITOR_IMG_NAME = "editormd-image-file";
    private static final String AVATAR = "avatar";
    private final String IMAGE_TYPE = ".jpg";
    @Value("${endpoint}")
    private String endpoint;
    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${accessKeySecret}")
    private String accessKeySecret;
    @Value("${bucketName}")
    private String bucketName;
    @Value("${imgUploadPath}")
    private String imgUploadPath;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Reference(version = "${demo.service.version}")
    private TopicService topicService;
    @Reference(version = "${demo.service.version}")
    private UserService userService;

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid;
    }

    @PostMapping("/topic/update")
    public String topicUpdate(@RequestBody Topic topic) {
        topicService.topicUpdate(topic);
        String url = "/topic/" + topic.getId();
        return url;
    }

    @PostMapping("/topic/delete/id")
    public String topicDeleteById(@RequestBody Topic topic) {
        topicService.deleteTopicById(topic.getId());
        return "1";
    }


    @PostMapping("/topic/total")
    public String indexTopic(HttpServletRequest request) throws JsonProcessingException {
        // 请求所有Topic
        List<Topic> topics = topicService.totalTopic();

        // 请求所有对应User
        List<Integer> ids = new ArrayList<>();
        for (Topic topic : topics)
            ids.add(topic.getUserId());

        List<User> users = userService.patchGetUser(ids);

        // 组装成 DTO
        UserAndTopic[] uats = new UserAndTopic[topics.size()];
        for (int i = 0; i < topics.size(); i++) {
            Topic topic = topics.get(i);
            for (int j = 0; j < users.size(); j++) {
                User user = users.get(j);
                if (topic.getUserId() == user.getId()) {
                    uats[i] = new UserAndTopic(topic, user);
                    break;
                }
            }
        }

        request.setAttribute("uats", uats);

        return objectMapper.writeValueAsString(uats);
    }

    @PostMapping("/topic/add")
    public String topicAdd(@RequestBody Topic topic, HttpServletRequest request) throws JsonProcessingException {
        User user = (User) request.getSession().getAttribute("user");
        topic.setUserId(user.getId());

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = new Date();
        topic.setTime(formatter.format(time));

        topicService.addTopicT(topic);

        String url = "/topic/history/" + user.getId();

        return url;
    }



    @PostMapping("/image/upload")
    public String imageUpload(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(EDITOR_IMG_NAME);
        if (file == null) {
            file = multipartRequest.getFile(AVATAR);
        }

        // 生成UUID用来代替上传文件的文件名
        String filename = getUUID() + IMAGE_TYPE;

        // 以下是上传图片的代码
        InputStream inputStream = null;
        ObsClient obsClient = null;
        String url = null;
        ImgUploadDTO imgUploadDTO = new ImgUploadDTO();
        try {
            inputStream = file.getInputStream();

            // 创建OBSClient实例。
            obsClient = new ObsClient(accessKeyId, accessKeySecret, endpoint);

            // 上传图片
            PutObjectResult result = obsClient.putObject(bucketName, filename, inputStream);

            imgUploadDTO.setSuccess(1);
            imgUploadDTO.setMessage("上传成功");
            imgUploadDTO.setUrl(result.getObjectUrl());
        } finally {
            // 关闭OSSClient。
            if (obsClient != null) {
                try {
                    obsClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 关闭文件流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return objectMapper.writeValueAsString(imgUploadDTO);
    }
}
